package appapi.service.impl;

import appapi.Global.BusinessException;
import appapi.Request.InspectionPageReq;
import appapi.Request.record.InspectionReq;
import appapi.Vo.EquipMaintenanVo;
import appapi.Vo.MaintenanPageVo;
import appapi.Vo.record.AddMaintenanVo;
import appapi.Vo.record.EditMaintenanDetailVo;
import appapi.Vo.record.EditMaintenanVo;
import appapi.dao.*;
import appapi.dto.AddEquipMaintenanDto;
import appapi.dto.AnnexType;
import appapi.entity.Zhongjiao.*;
import appapi.entity.app.AnnexEntity;
import appapi.entity.app.RectificationEntity;
import appapi.entity.basic.MaintenanItemEntity;
import appapi.entity.basic.UserInfo;
import appapi.service.IEquipmentMaintenanService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author djq
 * @date 2023/5/22 14:36
 * @description:
 */
@Component
public class EquipmentMaintenanServiceImpl implements IEquipmentMaintenanService {
    @Resource
    EquipmentmaintenanMapper equipmentmaintenanMapper;
    @Resource
    MaintenandetailMapper maintenandetailMapper;
    @Resource
    MaintenanitemMapper maintenanitemMapper;
    @Resource
    StaffMapper staffMapper;
    @Resource
    RectificationMapper rectificationMapper;
    @Resource
    AnnexMapper annexMapper;

    @Override
    public List<MaintenanPageVo> SelectMaintenanPage(UserInfo userInfo, InspectionPageReq dto) {
        //如果什么都没传,则查到该账号的所属机构显示数据
        if (dto.getOrgaPathIds() == null) {
            //拿到人员信息
            Map<String, Object> staffDto = staffMapper.selectStaffDetail(userInfo.getUserid());
            String orgaPathIds = staffDto.get("orgaPathIds").toString();
            dto.setOrgaPathIds(orgaPathIds);
        }

        PageHelper.startPage(dto.getCurrPage(), dto.getPageSize());
        return equipmentmaintenanMapper.selectMaintenanPage(dto);
    }

    @Override
    public List<MaintenanPageVo> SelectMaintenanPageNotoken(InspectionPageReq dto) {

        PageHelper.startPage(dto.getCurrPage(), dto.getPageSize());
        return equipmentmaintenanMapper.selectMaintenanPage(dto);
    }

    @Override
    public List<Map<String, Object>> SelectGetMaintenanList(Long equipId) {
        return equipmentmaintenanMapper.selectMaintenanList(equipId);
    }


    /**
     * 新增一条维保
     *
     * @param addDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int InsertMaintenan(AddEquipMaintenanDto addDto) {

        addDto.setCreateTime(LocalDateTime.now());
        addDto.setUpdateTime(LocalDateTime.now());
        EquipmentmaintenanDto dto = new EquipmentmaintenanDto();

        //转换维保详情
        List<MaintenandetailDto> detailList = addDto.getMainDetails().stream().map(detail -> {
            MaintenandetailDto detailDto = new MaintenandetailDto();
            BeanUtils.copyProperties(detail, detailDto);
            detailDto.setMaintenanImgs(detail.getImgs() == null ? "" : String.join(",", detail.getImgs()));
            return detailDto;
        }).collect(Collectors.toList());

        //转换维保记录
        BeanUtils.copyProperties(addDto, dto);
        //新增维保记录
        if (equipmentmaintenanMapper.insertSelective(dto) == 0) {
            return 0;
        }

        List<String> expList = new ArrayList<>();
        detailList.forEach(map -> {
            map.setCreateTime(LocalDateTime.now());
            map.setUpdateTime(LocalDateTime.now());
            map.setAuditState(0);
            map.setMainId(dto.getMainId());
            if (map.getMaintenanResult() == 1) {
                expList.add(map.getMaintenanName());
            }
        });
        //新增详情
        if (detailList.size() > 0) {
            maintenandetailMapper.insertList(detailList);
        }

        //如有异常则加入整改表
        if (expList.size() > 0) {
            //异常，添加整改信息
            List<RectificationEntity> rectList = new ArrayList<>();
            RectificationEntity rectEntity = new RectificationEntity();
            rectEntity.setRectItem(String.join(",", expList));
            rectEntity.setRectRequire(dto.getExpRequire());
            rectEntity.setEquipId(dto.getEquipId());
            rectEntity.setRectState(0);
            rectEntity.setRectAdd(1);
            rectEntity.setRectSource(dto.getMainId());
            rectEntity.setRectType(AnnexType.AnnexTypeEnum.maintenan.getCode());
            rectEntity.setRectDate(new Date());
            rectEntity.setCreateTime(LocalDateTime.now());
            rectEntity.setUpdateTime(LocalDateTime.now());
            rectEntity.setSoutOper(addDto.getCreateUser());
            rectList.add(rectEntity);
            rectificationMapper.insertBatch(rectList);
        }
        //有附件则新增附件
        if (addDto.getAnnexUrl() != null && addDto.getAnnexUrl().size() > 0) {
            //暂搁置
            //String[] user = JwtUtil.getUserInfoByJwtToken(request);
            List<AnnexEntity> annexCollect = addDto.getAnnexUrl().stream().map(annex -> {
                AnnexEntity annexEntity = new AnnexEntity();
                annexEntity.setCreateTime(LocalDateTime.now());
                annexEntity.setUpdateTime(LocalDateTime.now());
                annexEntity.setAnnexTitle("维保");
                annexEntity.setAnnexType(AnnexType.AnnexTypeEnum.maintenan.name());
                annexEntity.setAnnexUrl(annex);
                annexEntity.setCreateUser(addDto.getCreateUser());
                return annexEntity;
            }).collect(Collectors.toList());

            annexMapper.insertList(annexCollect);
        }

        return 1;
    }

    /**
     * 修改维保及其维保项目
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void UpdateMaintenan(EquipmentmaintenanDto dto) {
        dto.setUpdateTime(LocalDateTime.now());
        if (equipmentmaintenanMapper.updateByPrimaryKeySelective(dto) == 0) {
            throw new BusinessException(500, "修改失败!");
        }
        //删除记录历史详情
        maintenandetailMapper.deleteByMainId(dto.getMainId());

        dto.getMainDetails().forEach(map -> {
            map.setCreateTime(LocalDateTime.now());
            map.setUpdateTime(LocalDateTime.now());
            map.setAuditState(0);
            map.setMainId(dto.getMainId());
        });
        //新增详情
        maintenandetailMapper.insertList(dto.getMainDetails());

        //如有异常,则新增整改(暂搁置)
        if (dto.getMainState() == 2) {
//            RectificationDto rDto = new RectificationDto();
//            rDto.setRectType(5);
//            rDto.setRectItem();
//            rectificationMapper.insertSelective();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void DelMaintenan(Long mainId) {

        equipmentmaintenanMapper.deleteByPrimaryKey(mainId);

        maintenandetailMapper.deleteByMainId(mainId);
    }

    /**
     * 新增一条维保项目
     *
     * @param dto
     */
    @Override
    public void InsertMaintenanItem(MaintenanitemDto dto) {
        MaintenanItemEntity entity = new MaintenanItemEntity();
        entity.setEquipTypeId(dto.getEquipTypeId());
        entity.setItemName(dto.getItemName());
        if (maintenanitemMapper.count(entity) > 0) {
            throw new BusinessException(500, "该维保项目已存在!");
        }
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        maintenanitemMapper.insertSelective(dto);
    }

    @Override
    public EquipMaintenanVo SelectMaintenanDetail(Long maintenanId) {

        EquipmentmaintenanDto equipmentmaintenanDto = equipmentmaintenanMapper.selectByPrimaryKey(maintenanId);
        if (equipmentmaintenanDto == null) {
            throw new BusinessException(500,"您查询的数据为空，请重新数据");
        }
        List<MaintenandetailDto> maintenandetailDtos = maintenandetailMapper.selectAllByMainId(equipmentmaintenanDto.getMainId());
        EquipMaintenanVo vo = new EquipMaintenanVo();
        BeanUtils.copyProperties(equipmentmaintenanDto, vo);
        List<AnnexDto> annexDtos = annexMapper.selectAllByRecId(AnnexType.AnnexTypeEnum.maintenan.name(), maintenanId);
        vo.setAnnexUrl(annexDtos.stream().map(AnnexDto::getAnnexUrl).collect(Collectors.toList()));
        vo.setMaintenandetailDtos(maintenandetailDtos);
        return vo;
    }

    /**
     * 添加维保记录（包括维保记录、明细、生成整改记录、附件记录）
     *
     * @param vo
     * @return
     */
    @Override
    public int addInfo(AddMaintenanVo vo) {
        EquipmentmaintenanDto entity = vo.vo2Entity();
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        EquipmentmaintenanDto dto = new EquipmentmaintenanDto();
        //添加维保记录
        int iRet = equipmentmaintenanMapper.insert(entity);
        if (iRet > 0) {
            //记录ID
            Long mainId = entity.getMainId();
            //添加明细
            addDetail(mainId, vo.getMainDetails());
            //是否需要写整改
            List<EditMaintenanDetailVo> expList = vo.getMainDetails().stream()
                    .filter(EditMaintenanDetailVo -> EditMaintenanDetailVo.getMaintenanResult() == 1)
                    .collect(Collectors.toList());
            if (expList.size() > 0) {
                //异常，添加整改信息
                List<RectificationEntity> rectList = new ArrayList<>();
                List<String> itemList = expList.stream().map(EditMaintenanDetailVo::getMaintenanName).collect(Collectors.toList());
                List<String> imgUrl = new ArrayList<>();
                ;
                for (EditMaintenanDetailVo ex : expList
                ) {
                    ListUtils.union(imgUrl, ex.getImgs());
                }

                RectificationEntity rectEntity = new RectificationEntity();
                rectEntity.setRectItem(String.join(",", itemList));
                rectEntity.setRectRequire(vo.getExpRequire());
                rectEntity.setEquipId(vo.getEquipId());
                rectEntity.setRectState(0);
                rectEntity.setRectAdd(1);
                rectEntity.setRectSource(mainId);
                rectEntity.setRectType(AnnexType.AnnexTypeEnum.maintenan.getCode());
                rectEntity.setSoutOper(vo.getOperName());
                rectEntity.setRectDate(new Date());
                rectEntity.setCreateTime(LocalDateTime.now());
                rectEntity.setUpdateTime(LocalDateTime.now());
                rectEntity.setRectImgs(String.join(",", imgUrl));
                rectList.add(rectEntity);
                rectificationMapper.insertBatch(rectList);
            }
            //有附件则新增附件
            if (vo.getAnnexUrl().size() > 0) {
                addAnnex(mainId, vo.getOperName(), vo.getAnnexUrl());
            }
        }
        return iRet;
    }

    /**
     * 批量添加维保记录明细
     *
     * @param mainId
     * @param detailVos
     */
    private void addDetail(Long mainId, List<EditMaintenanDetailVo> detailVos) {
        List<MaintenandetailDto> detailList = new ArrayList<>();
        for (EditMaintenanDetailVo vo : detailVos
        ) {
            MaintenandetailDto entity = vo.vo2Entity();
            entity.setMainId(mainId);
            entity.setMaintenanImgs(String.join(",", vo.getImgs()));
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            detailList.add(entity);
        }
        if (detailList.size() > 0) {
            maintenandetailMapper.insertList(detailList);
        }
    }

    /**
     * 添加附件
     *
     * @param mainId
     * @param operName
     * @param annexList
     */
    private void addAnnex(Long mainId, String operName, List<String> annexList) {
        List<AnnexEntity> annexCollect = annexList.stream().map(annex -> {
            AnnexEntity annexEntity = new AnnexEntity();
            annexEntity.setCreateTime(LocalDateTime.now());
            annexEntity.setUpdateTime(LocalDateTime.now());
            annexEntity.setAnnexTitle("维保");
            annexEntity.setAnnexType(AnnexType.AnnexTypeEnum.maintenan.name());
            annexEntity.setRecId(mainId);
            annexEntity.setAnnexUrl(annex);
            annexEntity.setCreateUser(operName);
            return annexEntity;
        }).collect(Collectors.toList());
        annexMapper.insertList(annexCollect);
    }

    /**
     * 编辑维保记录（包括维保记录、明细、生成整改记录、附件记录）
     *
     * @param vo
     */
    @Override
    public int editInfo(EditMaintenanVo vo) {
        EquipmentmaintenanDto entity = vo.vo2Entity();
        entity.setUpdateTime(LocalDateTime.now());
        //编辑维保记录
        int iRet = equipmentmaintenanMapper.updateByPrimaryKey(entity);
        if (iRet > 0) {
            Long mainId = vo.getMainId();
            //删除维保明细
            maintenandetailMapper.deleteByMainId(mainId);
            // 删除整改记录
            rectificationMapper.deleteByRecId(AnnexType.AnnexTypeEnum.maintenan.getCode(), mainId);
            //添加明细
            addDetail(mainId, vo.getMainDetails());
            //是否需要写整改
            List<String> expList = vo.getMainDetails().stream()
                    .filter(EditMaintenanDetailVo -> EditMaintenanDetailVo.getMaintenanResult() == 1)
                    .map(EditMaintenanDetailVo::getMaintenanName)
                    .collect(Collectors.toList());
            if (expList.size() > 0) {
                List<RectificationEntity> rectList = new ArrayList<>();
                //异常，添加整改信息
                RectificationEntity rectEntity = new RectificationEntity();
                rectEntity.setRectItem(String.join(",", expList));
                rectEntity.setRectRequire(vo.getExpRequire());
                rectEntity.setEquipId(vo.getEquipId());
                rectEntity.setRectState(0);
                rectEntity.setRectAdd(1);
                rectEntity.setRectSource(mainId);
                rectEntity.setRectType(AnnexType.AnnexTypeEnum.maintenan.getCode());
                rectEntity.setSoutOper(vo.getOperName());
                rectEntity.setRectDate(new Date());
                rectEntity.setCreateTime(LocalDateTime.now());
                rectEntity.setUpdateTime(LocalDateTime.now());
                rectList.add(rectEntity);
                rectificationMapper.insertBatch(rectList);
            }

            annexMapper.deleteByRecId(AnnexType.AnnexTypeEnum.maintenan.name(), Collections.singletonList(mainId));
            //有附件则新增附件
            if (vo.getAnnexUrl().size() > 0) {
                addAnnex(mainId, vo.getOperName(), vo.getAnnexUrl());
            }
        }
        return iRet;
    }


    /**
     * 批量删除
     *
     * @param mainIds
     * @return
     */
    @Override
    public int deleteInfo(List<Long> mainIds) {
        int iRet = equipmentmaintenanMapper.deleteBatch(mainIds);
        if (iRet > 0) {
            //删除明细
            maintenandetailMapper.deleteByMainIds(mainIds);
            //删除整改信息
            rectificationMapper.deleteSourcesBatch(AnnexType.AnnexTypeEnum.maintenan.getCode(), mainIds);
        }
        return iRet;
    }

    @Override
    public PageInfo<MaintenanPageVo> getPage(InspectionPageReq req) {
        if (ObjectUtils.allNotNull(req.getCurrPage(), req.getPageSize())) {
            PageHelper.startPage(req.getCurrPage(), req.getPageSize());
        }
        List<MaintenanPageVo> list = equipmentmaintenanMapper.selectMaintenanPage(req);
        PageInfo pageInfo = new PageInfo(list);

        return pageInfo;
    }

    @Override
    public List<MaintenanPageVo> getList(InspectionReq req) {
        return equipmentmaintenanMapper.querytList(req);
    }

    @Override
    public List<MaintenanPageVo> getLists(InspectionPageReq req) {
        return equipmentmaintenanMapper.selectMaintenanPage(req);
    }

}
